<?php
defined('IN_XLP') or exit('Access Denied');

/*
 * 商品库存模型
 */
class goodsStockModel extends Model {

	function __construct() {
		parent::__construct();
	}


	/*
	 * 减少商品库存 增加下单量
	 */
	public function stockDec($goods_id, $num, $spec_id) {
		$info = M('goods')
			  ->field('`goods_spec`,`sale_count`,`storage_number`')
			  ->where(array('id'=>$goods_id))
			  ->find();

		//判断有无规格
		if($info['goods_spec']) {
			$spec_info = M('goods_spec')
					   ->field('`stock`,`sales_num`')
					   ->where(array('id'=>$spec_id))
					   ->find();
			$stock = $spec_info['stock'] - $num;
			$sales_num = $spec_info['sales_num'] + $num;
			M('goods_spec')->update(array('stock'=>$stock, 'sales_num'=>$sales_num), array('id'=>$spec_id));
		}

		$stock = $info['storage_number'] - $num;
		$sales_num = $info['sale_count'] + $num;
		M('goods')->update(array('storage_number'=>$stock, 'sale_count'=>$sales_num), array('id'=>$goods_id));
	}


    /*
     * 增加销量
     */
    public function soldInc($goods_id, $num, $spec_id) {
        $info = M('goods')
              ->field('`goods_spec`,`sold`')
              ->where(array('id'=>$goods_id))
              ->find();

        //判断有无规格
        if($info['goods_spec']) {
            $spec_info = M('goods_spec')
                       ->field('`sold`')
                       ->where(array('id'=>$spec_id))
                       ->find();
            $sold = $spec_info['sold'] + $num;
            M('goods_spec')->update(array('sold'=>$sold), array('id'=>$spec_id));
        }

        $sold = $info['sold'] + $num;
        M('goods')->update(array('sold'=>$sold), array('id'=>$goods_id));   
    }

    /*
     * 检查商品库存
     */
    public function checkStock($goods_id, $num, $spec_id) {
        $info = M('goods')
			  ->field('`goods_spec`,`storage_number`')
			  ->where(array('id'=>$goods_id))
			  ->find();

		if($info['goods_spec']) {
			$spec_info = M('goods_spec')
					   ->field('`stock`')
					   ->where(array('id'=>$spec_id))
					   ->find();
			return $spec_info['stock'] >= $num ? $spec_info['stock'] : false;
		} else {
			return $info['storage_number'] >= $num ? $info['storage_number'] : false;
		}
    }

    /*
     * 返回库存数量
     */
    public function getStock($goods_id, $spec_id) {
        $info = M('goods')
              ->field('`goods_spec`,`storage_number`')
              ->where(array('id'=>$goods_id))
              ->find();

        if($info['goods_spec']) {
            $spec_info = M('goods_spec')
                       ->field('`stock`')
                       ->where(array('id'=>$spec_id))
                       ->find();
            return $spec_info['stock'];
        } else {
            return $info['storage_number'];
        }
    }


}